package com.syyo.gulimall.seckill.service.impl;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.syyo.common.domain.ResultVo;
import com.syyo.common.to.mq.SeckillOrderTo;
import com.syyo.common.utils.MyJSONUtils;
import com.syyo.common.vo.MemberVo;
import com.syyo.gulimall.seckill.config.rabbit.MyMQConfig;
import com.syyo.gulimall.seckill.config.rabbit.MyRabbitConfig;
import com.syyo.gulimall.seckill.feign.CounponFeign;
import com.syyo.gulimall.seckill.feign.ProductFeign;
import com.syyo.gulimall.seckill.interceptor.LoginUserInterceptor;
import com.syyo.gulimall.seckill.service.SeckillService;
import com.syyo.gulimall.seckill.to.SeckillSkuRedisTo;
import com.syyo.gulimall.seckill.vo.SeckillSessionWithSkus;
import com.syyo.gulimall.seckill.vo.SeckillSkuRelationVo;
import com.syyo.gulimall.seckill.vo.SkuInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @author: wang
 * @date: 2021/5/20 17:57
 * @Description:
 */
@Slf4j
@Service
public class SeckillServiceImpl implements SeckillService {

    private final String SESSION_CACHE_PREFIX = "seckill:sessions:";
    private final String SKUKILL_CACHE_PREFIX = "seckill:skus";
    private final String SKU_STOCK_SEMAPHORE = "seckill:stock:";// +商品随机码

    @Autowired
    CounponFeign counponFeign;

    @Autowired
    ProductFeign productFeign;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    RedissonClient redissonClient;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Override
    public void uploadSeckillSku() {
        //1.去扫描参与秒杀活动的商品

        ResultVo resultVo = counponFeign.lastSession();
        if (resultVo.getCode() == 20000) {
            //
            List<SeckillSessionWithSkus> sessionData = MyJSONUtils.typeCast(new TypeReference<List<SeckillSessionWithSkus>>() {
            }, resultVo.getData());

            // 存入缓存
            // 缓存活动信息
            saveSessionInfos(sessionData);
            // 缓存活动关联的商品信息
            saveSessionSkuInfos(sessionData);
        }

    }

    /**
     * 获取当前的秒杀商品信息
     *
     * @return
     */
//    @SentinelResource(value = "getCurrentSeckillSkusResource",blockHandler = "blockHandler")
    @Override
    public List<SeckillSkuRedisTo> getCurrentSeckillSkus() {

        try (Entry entry = SphU.entry("seckillSkus")) {
            // 1.确定当前时间的秒杀场次
            long time = new Date().getTime();
            Set<String> keys = redisTemplate.keys(SESSION_CACHE_PREFIX + "*");
            for (String key : keys) {
                // seckill:sessions:1621533600000_1621537200000
                String replace = key.replace(SESSION_CACHE_PREFIX, "");
                String[] s = replace.split("_");
                long start = Long.parseLong(s[0]);
                long end = Long.parseLong(s[1]);
                if (time >= start && time <= end) {
                    // 2.获取这个场次的商品信息
                    List<String> range = redisTemplate.opsForList().range(key, -100, 100);

                    BoundHashOperations<String, String, String> redisHash = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
                    List<String> list = redisHash.multiGet(range);

                    if (list != null && list.size() > 0) {
                        List<SeckillSkuRedisTo> collect = list.stream().map(item -> {
                            SeckillSkuRedisTo redisTo = JSON.parseObject(item, SeckillSkuRedisTo.class);
                            redisTo.setRandomCode("");
                            return redisTo;
                        }).collect(Collectors.toList());
                        return collect;
                    }
                    break;
                }
            }
        } catch (BlockException e) {
            log.error("资源被限流{}", e.getMessage());
        }
        return null;
    }

    public List<SeckillSkuRedisTo> blockHandler(BlockException e) {
        log.error("getCurrentSeckillSkusResource被限流了,{}",e.getMessage());
        return null;
    }

    /**
     * 获取商品秒杀预告信息
     *
     * @param skuId
     * @return
     */
    @Override
    public SeckillSkuRedisTo getSkuSeckillInfo(Long skuId) {
        //找到商品的所有key
        BoundHashOperations<String, String, String> redisHash = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
        Set<String> keys = redisHash.keys();
        if (keys != null && keys.size() > 0) {
            String regx = "\\d-" + skuId;
            for (String key : keys) {
                // key=1-11  1：场次id，11：skuId
                if (Pattern.matches(regx, key)) {
                    String json = redisHash.get(key);
                    SeckillSkuRedisTo redisTo = JSON.parseObject(json, SeckillSkuRedisTo.class);

                    // 处理随机码，如果是在活动时间内就返回，不是就返回null
                    long time = new Date().getTime();
                    if (time >= redisTo.getStartTime() && time <= redisTo.getEndTime()) {

                    } else {
                        redisTo.setRandomCode(null);
                    }
                    return redisTo;
                }
            }
        }
        return null;

    }

    @Override
    public String kill(String killId, String key, Integer num) {
        long s1 = System.currentTimeMillis();
        //获取当前用户的信息
        MemberVo user = LoginUserInterceptor.loginUser.get();
        //1、获取当前秒杀商品的详细信息从Redis中获取
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
        String json = hashOps.get(killId);
        if (StringUtils.isEmpty(json)) {
            return null;
        }
        //(合法性效验)
        SeckillSkuRedisTo redisTo = JSON.parseObject(json, SeckillSkuRedisTo.class);
        Long startTime = redisTo.getStartTime();
        Long endTime = redisTo.getEndTime();
        long currentTime = System.currentTimeMillis();
        //判断当前这个秒杀请求是否在活动时间区间内(效验时间的合法性)
        if (currentTime >= startTime && currentTime <= endTime) {

            //2、效验随机码和商品id
            String randomCode = redisTo.getRandomCode();
            String skuId = redisTo.getPromotionSessionId() + "-" + redisTo.getSkuId();
            if (randomCode.equals(key) && killId.equals(skuId)) {
                //3、验证购物数量是否合理和库存量是否充足
                Integer seckillLimit = redisTo.getSeckillLimit();

                //获取信号量
                String seckillCount = redisTemplate.opsForValue().get(SKU_STOCK_SEMAPHORE + randomCode);
                Integer count = Integer.valueOf(seckillCount);
                //判断信号量是否大于0,并且买的数量不能超过库存
                if (count > 0 && num <= seckillLimit && count >= num) {
                    //4、验证这个人是否已经买过了（幂等性处理）,如果秒杀成功，就去占位。userId-sessionId-skuId
                    //SETNX 原子性处理
                    String redisKey = user.getId() + "-" + skuId;
                    //设置自动过期(活动结束时间-当前时间)
                    Long ttl = endTime - currentTime;
                    Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent(redisKey, num.toString(), ttl, TimeUnit.MILLISECONDS);
                    if (aBoolean) {
                        //占位成功说明从来没有买过,分布式锁(获取信号量-1)
                        RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + randomCode);
                        //TODO 秒杀成功，快速下单
//                        boolean semaphoreCount = semaphore.tryAcquire(num, 100, TimeUnit.MILLISECONDS);
                        boolean semaphoreCount = semaphore.tryAcquire(num);
                        //保证Redis中还有商品库存
                        if (semaphoreCount) {
                            //创建订单号和订单信息发送给MQ
                            // 秒杀成功 快速下单 发送消息到 MQ 整个操作时间在 10ms 左右
                            String timeId = IdWorker.getTimeId();
                            SeckillOrderTo orderTo = new SeckillOrderTo();
                            orderTo.setOrderSn(timeId);
                            orderTo.setMemberId(user.getId());
                            orderTo.setNum(num);
                            orderTo.setPromotionSessionId(redisTo.getPromotionSessionId());
                            orderTo.setSkuId(redisTo.getSkuId());
                            orderTo.setSeckillPrice(redisTo.getSeckillPrice());
                            rabbitTemplate.convertAndSend(MyMQConfig.ORDER_EXCHANGE, MyMQConfig.ORDER_SECKILL_KEY, orderTo);
                            long s2 = System.currentTimeMillis();
                            log.info("耗时..." + (s2 - s1));
                            return timeId;
                        }
                    }
                }
            }
        }
        long s3 = System.currentTimeMillis();
        log.info("耗时..." + (s3 - s1));
        return null;
    }

    private void saveSessionInfos(List<SeckillSessionWithSkus> sessionData) {
        System.out.println("保存活动信息");
        sessionData.stream().forEach(session -> {
            long startTime = session.getStartTime().getTime();
            long endTime = session.getEndTime().getTime();
            String key = SESSION_CACHE_PREFIX + startTime + "_" + endTime;
            Boolean hasKey = redisTemplate.hasKey(key);
            if (!hasKey) {
                List<String> skuIds = session.getRelationSkus().stream().map(item ->
                        // 1_2   场次id_skuId
                        item.getPromotionSessionId().toString() + "-" + item.getSkuId().toString()
                ).collect(Collectors.toList());
                // 缓存活动信息
                redisTemplate.opsForList().leftPushAll(key, skuIds);
            }
        });
    }

    private void saveSessionSkuInfos(List<SeckillSessionWithSkus> sessionData) {
        System.out.println("保存活动关联的商品信息");
        sessionData.stream().forEach(session -> {
            // 准备hash操作
            BoundHashOperations<String, Object, Object> redisHash = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);

            for (SeckillSkuRelationVo seckillSkuVo : session.getRelationSkus()) {
                // 1_2   场次id_skuId
                String key = seckillSkuVo.getPromotionSessionId().toString() + "-" + seckillSkuVo.getSkuId().toString();
                if (!redisHash.hasKey(key)) {
                    SeckillSkuRedisTo redisTo = new SeckillSkuRedisTo();
                    // 1.sku的基本信息
                    ResultVo result = productFeign.getSkuInfo(seckillSkuVo.getSkuId());
                    if (result.getCode() == 20000) {
                        SkuInfoVo skuInfoVo = MyJSONUtils.typeCast(new TypeReference<SkuInfoVo>() {
                        }, result.getData());
                        redisTo.setSkuInfo(skuInfoVo);
                    }
                    // 2.sku的秒杀信息
                    BeanUtils.copyProperties(seckillSkuVo, redisTo);

                    // 3.设置秒杀时间信息
                    redisTo.setStartTime(session.getStartTime().getTime());
                    redisTo.setEndTime(session.getEndTime().getTime());

                    // 4.设置商品的随机码
                    String token = UUID.randomUUID().toString().replace("-", "");
                    redisTo.setRandomCode(token);

                    String jsonString = JSON.toJSONString(redisTo);
                    redisHash.put(key, jsonString);

                    // 如果当前场次的商品的库存信息已经上架就不需要上家


                    //5.使用库存作为分布式信号量 限流
                    RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + token);
                    // 商品的秒杀数量作为信号量
                    semaphore.trySetPermits(seckillSkuVo.getSeckillCount());
                }
            }
        });

    }
}
